<template>
  <div class="index-conntainer">
    <div class="content">
      
      <!-- 查询条件 -->
      <div class="search-container">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item :label="t('employee.loginName')" prop="loginName">
            <el-input
              v-model="queryParams.loginName"
              :placeholder="t('employee.loginName')"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
           
          
          <el-form-item>
            <el-button type="primary" @click="handleQuery()"><i-ep-search />{{ t('common.search') }}</el-button>
            <el-button @click="resetQuery()"><i-ep-refresh />{{ t('common.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button
                     type="primary"
                     plain
                     :icon="Plus"
                       v-if="isRoot"
                     @click="handleAdd">{{ t('common.add') }}</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     type="success"
                     plain
                    icon="icon-edit"
                    :disabled="single"
                    v-if="isRoot"
                    @click="handlerUpdate()"
                  >{{ t('common.modi') }}</el-button>
               </el-col>
               
               <el-col :span="1.5">
                   <el-button
                      type="danger"
                      plain
                      icon="icon-delete-themes"
                      :disabled="multiple"
                      @click="handlerDelete()"
                      v-if="isRoot"
                   >{{ t('common.remove') }}</el-button>
                </el-col>
                
           
             <el-col :span="1.5">
                <el-button
                   type="success"
                   plain
                  icon="icon-edit"  
                  @click="handlerExcel()"
                >{{ t('common.exportexcel') }}</el-button>
             </el-col>
             
            </el-row>
            
      <!--表格显示数据 -->
      <el-table v-loading="loading" :data="rows" @selection-change="handleSelectionChange" >
           <el-table-column type="selection" width="55" align="center" />
           <el-table-column :label="t('common.id')" align="center" prop="id" width="80" />
           <el-table-column :label="t('employee.loginName')" align="center" prop="loginName" />
           <el-table-column :label="t('employee.gender')" align="center">
              <template #default="scope">
                <template  v-for="item in sys_user_sex" >
                  <el-tag  effect="dark" :type="item.elTagType"  v-if="item.value==scope.row.gender" >{{ item.label}}</el-tag>   
                </template> 
              </template>              
           </el-table-column>         
           <el-table-column :label="t('employee.avatar')" align="center"  width="200">  
             <template #default="scope">
                <img :src="scope.row.avatar"  width="150">            
             </template>     
           </el-table-column>
           <el-table-column :label="t('employee.status')" align="center" prop="status" >    
              <template #default="scope">
                
                <template  v-for="item in sys_normal_disable" >
                  <el-tag  effect="dark" :type="item.elTagType"  v-if="item.value==scope.row.status" >{{ item.label}}</el-tag>   
                </template>  
                    
              </template>              
           </el-table-column>
           
           <el-table-column :label="t('common.createTime')" align="center" prop="createTime" />
          
           <el-table-column :label="t('common.operate')" width="250" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                 <el-button link type="primary" icon="icon-edit" v-if="isRoot || scope.row.loginName===currentName" @click="handlerUpdate(scope.row)"  >{{t('common.modi')}}</el-button>
                 
                 
                 <el-button link type="primary" icon="icon-delete-themes" v-if="isRoot"  @click="handlerDelete(scope.row)" >{{t('common.remove')}}</el-button>
                 
                 <el-button link type="primary" icon="icon-setting" v-if="isRoot || scope.row.loginName===currentName"  @click="handlerChangPwd(scope.row)" >{{t('common.resetpwd')}}</el-button>
                 
              </template>
           </el-table-column>
        </el-table>
          
         <el-pagination
              v-if="total>0"
              v-model:current-page="queryParams.page"
              v-model:page-size="queryParams.size"
              :page-sizes="[10, 20, 30, 40,50,100]"
              small="small"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
      
      <!-- 添加或修改岗位对话框 -->
         <el-dialog :title="title" v-model="open" width="700px" append-to-body :close-on-click-modal="false" @closed="reset">
            <el-form ref="postRef" :model="form"   label-width="80px">
                <el-form-item v-if="!form.id" :label="t('employee.loginName')" prop="name"  :rules="[{ required: true, message: t('common.required'), trigger: 'blur' },{validator:mobileValidator,trigger: 'blur'}]">
                   <el-input v-model="form.name" placeholder="请输入账号(账号为手机号)" />
                </el-form-item>
                
                <el-form-item v-if="!form.id" :label="t('login.password')" prop="password" :rules="[{ required: true, message: t('common.required'), trigger: 'blur' }]">
                  <el-input type="password" v-model="form.password" :placeholder="t('login.rules.password')" />
               </el-form-item>
               
               <el-form-item v-if="!form.id" label="确认密码" prop="confirmPwd" :rules="[{ required: true, message: t('common.required'), trigger: 'blur' },{validator:validatePass2,trigger: 'blur'}]">
                  <el-input type="password" v-model="form.confirmPwd" placeholder="请输入再次输入名称" />
               </el-form-item>
               
               <el-form-item :label="t('employee.gender')" prop="gender" :rules="[{ required: true, message: t('common.required'), trigger: 'blur' }]">
                   <el-radio-group v-model="form.gender">
                      <el-radio
                         v-for="sex in sys_user_sex"
                         :key="sex.value"
                         :label="sex.value"
                      >{{ sex.label }}</el-radio>
                   </el-radio-group>
                </el-form-item>
                 
              
                 <el-form-item :label="t('employee.avatar')" prop="avatar" :rules="[{ required: true, message: t('common.required'), trigger: 'blur' }]">
                   <el-upload
                       class="avatar-uploader"
                      :action="imageUploadUrl"
                       :headers="header"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeAvatarUpload"
                     >
                       <img v-if="form.avatar" :src="form.avatar" class="avatar" width="175" />
                       <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                     </el-upload>
                 </el-form-item>
                 
                 
                 <el-form-item :label="t('employee.status')" prop="status" :rules="[{ required: true, message: t('common.required'), trigger: 'blur' }]">
                    <el-radio-group v-model="form.status">
                       <el-radio
                          v-for="dict in sys_normal_disable"
                          :key="dict.value"
                          :label="dict.value"
                       >{{ dict.label }}</el-radio>
                    </el-radio-group>
                 </el-form-item>
               
             </el-form>
          <template #footer>
             <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">{{ t('btn.confirm') }}</el-button>
               <el-button @click="cancelForm">{{ t('btn.cancel') }}</el-button>
             </div>
          </template>
       </el-dialog>
       
       
       <!-- 修改密码对放框 -->
          <el-dialog title="更改密码" v-model="openPwd" width="500px" append-to-body :close-on-click-modal="false" @closed="closePwdForm">
             <el-form ref="pwdRef" :model="pwdForm"   label-width="80px">
                 <el-form-item  label="新密码" prop="password" :rules="[{ required: true, message: t('common.required'), trigger: 'blur' }]">
                   <el-input type="password" v-model="pwdForm.password" placeholder="请输入密码" />
                </el-form-item>
                
                <el-form-item   label="确认密码" prop="confirmPwd" :rules="[{ required: true, message: t('common.required'), trigger: 'blur' },{validator:validatePwdPass2,trigger: 'blur'}]">
                   <el-input type="password" v-model="pwdForm.confirmPwd" placeholder="请输入再次输入密码" />
                </el-form-item> 
              </el-form>
           <template #footer>
              <div class="dialog-footer">
                 <el-button type="primary" @click="submitPwdForm">{{ t('btn.confirm') }}</el-button>
                 <el-button @click="cancelPwdForm">{{ t('btn.cancel') }}</el-button>
              </div>
           </template>
        </el-dialog>
      
    </div>
  </div>
</template>

<script setup>  
  import { ref} from 'vue'
  import { Plus } from '@element-plus/icons-vue' 
  import { ElMessage } from 'element-plus'
  import store from '@/store/index.js'
  //定义国际化的语言的文件
  import { useI18n } from 'vue-i18n';
  const { t } = useI18n();
  
  //组合式函数(代码重复的问题)
  import { usePage } from '@/composables/PageComp.js'
  import { useAddAndEdit } from '@/composables/AddAndEditComp.js'
  
  import {dataApi, addApi, updateApi ,findByIdApi, changePasswordApi} from '@/api/employee.js'
  //图片上传地址
  const imageUploadUrl =ref(process.env.VUE_APP_BASE_API+'/api/upload/image')
  const { proxy } = getCurrentInstance(); 
  
  // 只要是读取sys_dict_data数据，我们就采用组合式函数方法
  const {sys_user_sex,sys_normal_disable} = proxy.useDict('sys_user_sex','sys_normal_disable');
   
   
  //通用数据必须要有的
  const reactiveObject = ref({
     dataApi: dataApi,
     addApi: addApi,
     updateApi: updateApi,
     findByIdApi: findByIdApi,
     removeApi: undefined,
     proxy: proxy,
     //这里要变，主键名称
     primaryKey: 'id'
    }); 
  
  //分页查询
  const { loading, total,rows ,queryParams,ids,single,multiple , handleQuery, resetQuery, handleSizeChange , handleCurrentChange, getList,handleSelectionChange }=usePage(reactiveObject)
  
  //新增和修改
  const { open,title,form,reset,cancelForm,submitForm,handlerUpdate,handleAdd ,beforeAvatarUpload ,handlerDelete}=useAddAndEdit(reactiveObject)
  
  
  
  //自己的定义额外参数
  const data = reactive({
    header: {
      'Authorization': store.getters['user/accessToken']
    },
  });
  
  ///自己的定义额外参数,用来使用的
  const { header} = toRefs(data);
  
  //初始化新装和修改的对话框的数据(必须要有)
  function initFormData(){
    form.value= {
      avatar: undefined,
      gender: '0',
      status: '0'
    }
  }
  
  initFormData()
  
  //文件上传成功
  function handleAvatarSuccess(res, file) {
    if(res.code===200){
       form.value.avatar= res.data.image_url
    }else{
       ElMessage.error( res.msg);
    } 
   } 
  
   //自定义表单验证（实际情况来选项配置）
    function validatePass2(rule, value, callback) { 
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== form.value.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    
    //自定义表单验证 （实际情况来选项配置）
    function mobileValidator(rule, value, callback){
      const regex=/1[3,4,5,6,8,9]\d{9}/ 
      if (value === '') {
        callback(new Error('手机号不能为空'));
      } else if (!regex.test(value)) {
        callback(new Error('手机号码格式不正确，只支持(13|14|15|17|18|19)开头的!'));
      } else {
        callback();
      }
    }
    
    //计算属性
    const isRoot = computed(() => {
      return store.getters['user/root']==="1";
    });
    
    const currentName = computed(() => {
      return store.getters['user/username']
    })
    
    
    //修改密码代码
    const pwdForm=ref({})
    const openPwd=ref(false)
    
    //关闭对话框
    function closePwdForm(){
      pwdForm.value={}
      //pwdRef
      proxy.$refs["pwdRef"].resetFields();
      openPwd.value= false
    }
    
    //关闭密码修改框
    function cancelPwdForm(){
      closePwdForm();
    }
  
    //提交密码修改
    function submitPwdForm(){
      
      proxy.$refs["pwdRef"].validate(valid => {
         if(valid){
            
            ElMessageBox.confirm(
               '确定要提交修改的密码吗?','询问',
               {
                 confirmButtonText: '确定',
                 cancelButtonText: '取消',
                 type: 'danger',
               }
             )
             .then(() => {
                 changePasswordApi(pwdForm.value).then(resp=> {
                    ElMessage({ message: '密码修改成功',type: 'success'});
                    // 判断 是否要重新登录，如果当前修改是自己的密码，你就必须要重新登录了
                    console.log(pwdForm.value.name==currentName.value)
                    if(pwdForm.value.name==currentName.value){
                      store.dispatch('user/logout').then(resp=> {
                        // 重新刷新
                        location.reload();
                        
                      });
                    }  
                    closePwdForm();                     
                 })
                
             })
             .catch(() => {
             }) 
             
         }       
      });           
    }
    
    //点击修改密码对话框
    function handlerChangPwd(row){
      //主键
      pwdForm.value.id=row.id
      //主要是修改成功以后，是否要重新登录用,因为登录的时候没有获取ID
      pwdForm.value.name=row.loginName
      //打开对话框
      openPwd.value= true
    }
    
    function validatePwdPass2(rule, value, callback) { 
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== pwdForm.value.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
  
  
  //导出数据到excel中
  function handlerExcel(){
    proxy.download('/api/employee/excel', queryParams.value, '后台员工信息.xlsx');
  }
  
</script>

<style scoped>
</style>
